import React, { Component } from 'react';
import { Button, ButtonProps } from 'antd';
import SliderCaptchaModal from '../slider_captcha';
import styles from './index.less';
import { message } from 'antd';
import { StringUtils } from 'xo-web-base';
interface SendSmsButtonProps extends ButtonProps {
  /**
   * 要发送的手机号
   */
  mobile: () => string;
  /**
   * 验证码类型 1-手机号注册 2-修改密码获取验证码 3-手机验证码登录
   */
  sendType: number;
}

interface SendSmsButtonState {
  /**
   * 滑块对话框是否可见
   */
  visible: boolean;
  /**
   * 当前计时数
   */
  count: number;
}

export default class SendSmsButton extends Component<
  SendSmsButtonProps & React.RefAttributes<HTMLElement>,
  SendSmsButtonState
> {
  state = {
    visible: false,
    count: this.refreshCount(),
  };

  timer: NodeJS.Timer = setInterval(() => {
    this.refreshCount();
  }, 1000);

  sliderCaptcha: SliderCaptchaModal | null = null;

  componentDidMount() {
    this.refreshCount();
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  /**
   * 刷新剩余倒计时
   * @returns 剩余时长
   */
  refreshCount() {
    const { sendType } = this.props;
    let count = 0;
    try {
      const lastTime = localStorage.getItem(`send_sms_time_${sendType}`);
      if (lastTime) {
        const now = Date.now();
        // 60为需要等待的秒数
        // (当前时间 - 上次发送时间) / 1000 等于 上次发送经过的秒数
        count = 60 - Math.ceil((now - Number.parseInt(lastTime)) / 1000);
        count = count < 0 ? 0 : count;
      }
    } catch (e) {}
    this.setState({
      count: count,
    });
    return count;
  }

  onButtonClick = () => {
    const { mobile } = this.props;
    const m = mobile();
    const flag = StringUtils.checkMobile(m);
    if (flag) {
      this.sliderCaptcha?.store.getSliderCaptcha();
      this.setState({
        visible: true,
      });
    } else {
      message.error('请输入正确的手机号');
    }
  };

  onSuccess = () => {
    const { sendType } = this.props;
    this.setState({
      visible: false,
    });
    // 保存最后一次短信发送时间
    localStorage.setItem(`send_sms_time_${sendType}`, `${Date.now()}`);
    this.refreshCount();
  };

  render() {
    const { mobile, sendType } = this.props;
    const { visible, count } = this.state;
    return (
      <>
        <Button
          className={styles.sendsms_btn}
          type="primary"
          onClick={this.onButtonClick}
          disabled={count > 0}
        >
          {count > 0 ? `${count}s` : '发送验证码'}
        </Button>
        <SliderCaptchaModal
          ref={(e) => (this.sliderCaptcha = e)}
          mobile={mobile.call(this)}
          sendType={sendType}
          visible={visible}
          onCancel={() => {
            this.setState({
              visible: false,
            });
          }}
          onSuccess={this.onSuccess}
        />
      </>
    );
  }
}
